package com.study.controller;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.study.bean.Attributevalue;
import com.study.bean.Camid;
import com.study.bean.Firstbrands;
import com.study.bean.Firstgoods;
import com.study.bean.Lunbo;
import com.study.bean.Sort;
import com.study.bean.Users;
import com.study.biz.Firstbandsbiz;
import com.study.biz.Firstgoodsbiz;
import com.study.biz.Lunbobiz;
import com.study.biz.Sortbiz;
import com.study.biz.UsersBiz;
import com.study.util.CommonUtils;

/**/

@WebServlet("/shouye")
public class firstpageservlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private UsersBiz biz = new UsersBiz();

	@Override
	public String excute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		// 查询可以显示轮播图片
		Lunbobiz lbbiz = new Lunbobiz();
		List<Lunbo> lblist = lbbiz.selectShouye();
		request.setAttribute("lblist", lblist);

		Firstgoodsbiz biz = new Firstgoodsbiz();
		// 查询最新商品
		List<Firstgoods> listone = biz.newgoods();
		request.setAttribute("listgoods", listone);
		System.out.println(listone);
		// 查询热销产品
		List<Firstgoods> listtwo = biz.hotxiao();
		request.setAttribute("listsgoodl", listtwo);
		// 查询特价商品
		List<Firstgoods> listthree = biz.teijian();
		request.setAttribute("listgoodst", listthree);
		// 查询特价商品
		List<Firstgoods> listfour = biz.duijian();
		request.setAttribute("listgoodso", listfour);

		Firstbandsbiz brbiz = new Firstbandsbiz();
		// 查询康佳（KONKA）品牌
		List<Firstbrands> listfive = brbiz.goodskjian();
		request.setAttribute("listbrand", listfive);
		// 查询KKTV品牌
		List<Firstbrands> listsix = brbiz.goodskktv();
		request.setAttribute("listbrandkk", listsix);

		// 查询一级
		Sortbiz sbiz = new Sortbiz();
		List<Sort> sorts = sbiz.fulei();
		request.setAttribute("sorts", sorts);

		List<Sort> sortlists = sbiz.selectone();
		System.out.println("结合水" + sortlists);
		session.setAttribute("sortlists", sortlists);
		return "f:firstpage";
	}

	public String registers(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String tel = request.getParameter("telphone");
		String pwd = request.getParameter("pwd");
		System.out.println(tel + pwd);
		Users us = new Users(null, tel, null, "1", tel, pwd);
		System.out.println(us);
		// Users uss= biz.selectphone(tel);
		// System.out.println(uss+"yhdiuuwjd`");
		if (tel == null && pwd == null) {
			session.setAttribute("tipsone", "鐢佃瘽鍙风爜鍜屽瘑鐮佷笉鑳戒负绌�");
			System.out.println("娉ㄥ唽澶辫触");
			return "r:shouye";
		} /*
			 * else if(tel.equals(biz.selectphone(tel).getUphone())) {
			 * session.setAttribute("tipsone", "璇ョ數璇濆彿鐮佸凡娉ㄥ唽"); return
			 * "r:shouye"; }
			 */else {
			System.out.println("娉ㄥ唽鎴愬姛");
			int a = biz.register(us);
			System.out.println("cha" + a);
			return "r:shouye";
		}
	}

	// 鐢ㄦ埛鐧婚檰
	public String loginins(HttpServletRequest request, HttpServletResponse response) {
		String tel = request.getParameter("telphone");
		String pwd = request.getParameter("pwd");
		Users admin = biz.adminLogin(tel, pwd);

		System.out.println("鐢ㄦ埛鐧婚檰");
		if (admin == null) {
			System.out.println("鐧婚檰澶辫触");
			session.setAttribute("tipone", "鐢ㄦ埛鍚嶆垨鑰呭瘑鐮侀敊璇紒锛�");
			session.setMaxInactiveInterval(30);
			return "f:firstpage";
		} else {
			System.out.println("鐧婚檰鎴愬姛");
			request.setAttribute("tel", tel);
			return "r:shouye";
		}
	}

	// 退出登陆
	public String loginup(HttpServletRequest request, HttpServletResponse response) {
		// 获取用户对象
		Users user = (Users) session.getAttribute("admin");
		System.out.println("用户对是" + user);
		// 判断用户是否有效
		if (user != null) { // 将用户对象逐出Session
			session.removeAttribute("admin");

		}
		Object uid = session.getAttribute("uid");
		if (uid != null) {
			session.removeAttribute("uid");
		}

		return "r:shouye";
	}

	//

	// 登陆
	public String loginin(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=utf-8");
		JSONObject jsonObject = new JSONObject();
		String tel = request.getParameter("telphone");
		String pwd = request.getParameter("pwd");
		System.out.print(pwd + "***");
		Users admin = biz.adminLogin(tel, pwd);
		System.out.println(admin);
		System.out.println("用户登陆");
		if (admin == null) {
			System.out.println("登陆失败");
			jsonObject.put("tipsone", "电话或密码错误");
			jsonObject.put("res", "false");
		} else if (isMobile(tel) == false) {
			jsonObject.put("tipsone", "电话格式不正确");
			System.out.println("注册失败");
			jsonObject.put("res", "false");

		} else if (pwd.length() != 6) {
			jsonObject.put("tipsone", "请输入正确的6位密码");
			System.out.println("注册失败");
			jsonObject.put("res", "false");
		} else {
			System.out.println("登陆成功");
			session.setAttribute("admin", admin);
			session.setAttribute("uid", admin.getUid());
			// request.getSession().setAttribute("tel", tel);
			jsonObject.put("user", admin);
			jsonObject.put("res", "true");
		}
		return jsonObject.toJSONString();
	}

	public boolean isMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}

	// 注册
	public String register(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("application/json;charset=utf-8");
		JSONObject jsonObject = new JSONObject();
		System.out.println("用户注册");
		String tel = request.getParameter("telphone");
		String pwd = request.getParameter("pwd");
		System.out.println("电话是" + tel);
		System.out.println("密码是" + pwd + "mimashi");
		System.out.println(tel + pwd);
		Users us = new Users(null, tel, null, "男", tel, pwd);
		//
		Users users = biz.selectphone(tel);

		Object mcode = session.getAttribute("mobile_code");
		String user_code = request.getParameter("codes");

		System.out.println(mcode + "yzmashi" + "验证码是" + user_code);
		System.out.println(us);
		if (tel == null || tel.equals("") || pwd == null || pwd.equals("")) {
			jsonObject.put("tipsone", "电话和密码不能为空");
			System.out.println("注册失败");
			jsonObject.put("res", "false");
		} else if (!CommonUtils.isNotEmpty(mcode) || !CommonUtils.isNotEmpty(user_code)
				|| !mcode.toString().equals(user_code)) {
			jsonObject.put("tipstwo", "验证码错误");
			System.out.println("注册失败");
			jsonObject.put("res", "false");
		} else if (isMobile(tel) == false) {
			jsonObject.put("tipsone", "电话格式不正确");
			System.out.println("注册失败");
			jsonObject.put("res", "false");
		} else if (pwd.length() != 6) {
			jsonObject.put("tipsone", "请输入正确的6位密码");
			System.out.println("注册失败");
			jsonObject.put("res", "false");
		} else if (users != null) {
			System.out.println("该用户已经存在");
			jsonObject.put("tipsone", "该用户已经存在");
			jsonObject.put("res", "false");
		} else {
			System.out.println("注册成功");
			int uid = biz.register(us);
			us.setUid(uid);
			session.setAttribute("admin", us);

			session.setAttribute("uid", uid);
			System.out.println("用户注册的id是" + us.getUid());

			jsonObject.put("user", us);
			jsonObject.put("res", "true");
		}
		return jsonObject.toJSONString();
	}

	public String sms(HttpServletRequest request, HttpServletResponse response) {
		// 接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
		// 账户注册：请通过该地址开通账户http://sms.ihuyi.com/register.html
		// 注意事项：
		// （1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
		// （2）请使用APIID（查看APIID请登录用户中心->验证码短信->产品总览->APIID）及 APIkey来调用接口；
		// （3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
		response.setContentType("application/json;charset=utf-8");
		String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
		int mobile_code = (int) ((Math.random() * 9 + 1) * 100000); // 获取随机数
		// 将手机验证码存储session，此处设置过期时间为1分钟。大家在测试过程中，可以尽量把session时间设置的长一些。测试成功之后才调成1分钟
		session.setAttribute("mobile_code", mobile_code);
		session.setMaxInactiveInterval(600);
		String account = "C78169399"; // 查看用户名是登录用户中心->验证码短信->产品总览->APIID
		String password = "83fa1590d854ad829edbcb543987ab8e"; // 查看密码请登录用户中心->验证码短信->产品总览->APIKEY
		String mobile = request.getParameter("mobile");
		System.out.println("验证码是" + mobile_code);
		// 这里的内容，需要和短信模板的是一致的
		String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
		try {
			URL url = new URL(postUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);// 允许连接提交信息
			connection.setRequestMethod("POST");// 网页提交方式“GET”、“POST”
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestProperty("Connection", "Keep-Alive");
			StringBuffer sb = new StringBuffer();
			sb.append("account=" + account);
			sb.append("&password=" + password);
			sb.append("&mobile=" + mobile);
			sb.append("&content=" + content);
			OutputStream os = connection.getOutputStream();
			os.write(sb.toString().getBytes());
			os.close();

			String line, result = "";
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			while ((line = in.readLine()) != null) {
				result += line;
			}
			in.close();
			/*
			 * //解析返回的xml内容，获取第二个字节msg的内容 DocumentBuilder newDocumentBuilder =
			 * DocumentBuilderFactory.newInstance().newDocumentBuilder();
			 * Document parse = newDocumentBuilder.parse(new
			 * ByteArrayInputStream(result.getBytes())); NodeList nodes =
			 * parse.getFirstChild().getChildNodes(); String msg="提交失败";
			 * if(nodes.getLength()>=3) { msg = nodes.item(1).getTextContent();
			 * }
			 */
			return "{msg:\"提交成功\"}";
		} catch (Exception e) {
			e.printStackTrace();
			return "f:error";

		}
	}

	/**
	 * 第⑥个方法：验证手机验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public String check_mobile_code(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=utf-8");
		// 判断验证码是否正确，此处设置了验证码存储在session中的过期时间，所以过期了也会显示不正确
		Object mcode = session.getAttribute("mobile_code");
		String user_code = request.getParameter("mcode");
		JSONObject json = new JSONObject();
		if (CommonUtils.isNotEmpty(mcode) && CommonUtils.isNotEmpty(user_code) && mcode.toString().equals(user_code)) {
			json.put("msg", true);
		} else {
			json.put("msg", false);
		}
		return json.toJSONString();
	}

	public String sorts(HttpServletRequest request, HttpServletResponse response) {
		Sortbiz biz = new Sortbiz();
		List<Sort> sortlist = biz.selectSort(0);
		System.out.println("sorts查询父级");
		request.setAttribute("sortlist", sortlist);
		return "f:shouye";
	}



	public String selectones(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=utf-8");
		Sortbiz biz = new Sortbiz();
		String vaus = request.getParameter("value");
		System.out.println("数字是" + vaus);
		Integer valu = Integer.parseInt(vaus);
		List<Sort> sortlists = biz.selectSort(valu);
		System.out.print(sortlists);
		System.out.println("查询子级的所有值");
		return JSON.toJSONString(sortlists);

	}

	/*
<<<<<<< HEAD
	 * * public String selectlid(HttpServletRequest request, HttpServletResponse
=======
	 * public String selectlid(HttpServletRequest request, HttpServletResponse
>>>>>>> branch 'master' of https://gitee.com/liaowenbo0210/Electronic.git
	 * response) { response.setContentType("application/json;charset=utf-8");
	 * Sortbiz biz = new Sortbiz(); String vaus = request.getParameter("value");
	 * System.out.println("父级的lid数字是" + vaus); Integer valu =
	 * Integer.parseInt(vaus); List<Sort> lidlname = biz.lids(valu);
	 * System.out.print(lidlname); System.out.println("查询父级的名字是"); return
	 * JSON.toJSONString(lidlname);
	 */
	// 判断是否登录ajax请求
	public String islogin(HttpServletRequest request, HttpServletResponse response) {
		Object uid = session.getAttribute("uid");
		if (uid == null || "".equals(uid)) {
			return "false";
		}
		return "true";
	}

	// ajax请求头部分类
	public String geheadtype(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=utf-8");
		// 查询一级
		Sortbiz sbiz = new Sortbiz();
		List<Sort> sorts = sbiz.fulei();
		System.out.print(sorts.get(0) + "&&&");
		return JSON.toJSONString(sorts);
	}
}
